import { insertIntoTextarea } from '@gnlab/utils/env-browser/dom'
import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Form, Switch, Input, message, Spin, Button } from 'antd'
import type { TextAreaRef } from 'antd/lib/input/TextArea'
import { EditModal } from '@/desktop/components'
import services from '@/services'
import type { PersonCardAutoApplyConfig } from '@/services/features/person-card-auto-apply'
import { MessageVar } from '@/services/features/person-card-auto-apply'
import './index.module.less'

export { ReactComponent as Icon } from './icon.svg'

export function PersonCardAutoApply({ open, onClose }: { open: boolean; onClose: () => void }) {
  return <EditModal
    styleName="modal"
    title="名片自动加人"
    open={open}
    onCancel={onClose}
    width="650px"
  >
    {open ? <Content onClose={onClose} /> : null}
  </EditModal>
}

function Content(props: { onClose: () => void }) {
  const { onClose } = props

  const [config, setConfig] = useState<PersonCardAutoApplyConfig | null>(null)
  useAsyncEffect(async () => {
    const res = await services.features.personCardAutoApply.get()
    if (res.success) {
      setConfig(res.data)
    } else {
      void message.error(`名片加人配置获取失败：${res.error}`)
    }
  }, [])

  const [submitting, setSubmitting] = useState(false)
  const submit = useCallback(
    async (values: PersonCardAutoApplyConfig) => {
      setSubmitting(true)
      const res = await services.features.personCardAutoApply.save(values)
      setSubmitting(false)
      if (res.success) {
        void message.success('保存成功')
        onClose()
      } else {
        void message.error(`保存失败：${res.error}`)
      }
    },
    [onClose],
  )

  const [form] = Form.useForm()
  const messageRef = useRef<TextAreaRef>(null)
  const insertVariable = useCallback(
    (variable: string) => {
      const textarea = messageRef.current?.resizableTextArea?.textArea
      if (!textarea) return
      const result = insertIntoTextarea(textarea, `{${variable}}`)
      form.setFieldsValue({ message: result })
    },
    [form],
  )

  const textareaExtra = <div>
    <span>插入变量：</span>
    <a onClick={() => insertVariable(MessageVar.QywxName)}>我的企微昵称</a>
    <a onClick={() => insertVariable(MessageVar.ContactName)}>名片昵称</a>
    <a onClick={() => insertVariable(MessageVar.SenderName)}>名片发送者昵称</a>
  </div>

  return <main>
    <header>
      <div styleName="tips">
        开启名片自动加人后，当聊天中收到他人的名片，将自动通过名片发送添加好友申请。
      </div>
    </header>

    {!config ? (
      <div styleName="loading">
        <Spin tip="加载中..." size="large" />
      </div>
    ) : null}

    {config ? (
      <>
        <Form form={form} initialValues={config} labelCol={{ span: 4 }} onFinish={submit}>
          <Form.Item label="名片自动加人" name="enable" valuePropName="checked">
            <Switch checkedChildren="开" unCheckedChildren="关" />
          </Form.Item>

          <Form.Item
            label="验证消息"
            name="message"
            styleName="message"
            extra={textareaExtra}
            rules={[{ required: true, max: 48 }]}
          >
            <Input.TextArea
              placeholder="请输入加好友验证消息，不超过48个汉字。"
              rows={5}
              ref={messageRef}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button loading={submitting} type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </>
    ) : null}
  </main>
}
